package com.hbdl.web.sys.utils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import com.hbdl.common.constant.Constant;
import com.hbdl.common.spring.utils.SpringContextHolder;
import com.hbdl.common.utils.CacheUtils;
import com.hbdl.common.utils.PMSUtils;
import com.hbdl.common.utils.ResultUtil;
import com.hbdl.common.utils.TreeUtils2;
import com.hbdl.web.sys.model.Resources;
import com.hbdl.web.sys.model.User;
import com.hbdl.web.sys.service.SysResourceService;
import com.hbdl.web.sys.service.SysRoleService;

/**
 * @ClassName:SysUserUtils
 * @date:2015年2月4日 下午8:12:41
 * @author ?
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class SysUserUtils {

	private static final Logger logger = LoggerFactory.getLogger(SysUserUtils.class);

	static SysResourceService sysResourceService = SpringContextHolder.getBean("sysResourceService");
	static SysRoleService sysRoleService = SpringContextHolder.getBean("sysRoleService");

	/**
	 * 设置用户的认证
	 */
	public static void setUserAuth() {
		logger.debug("获取用户菜单，角色信息");

		// 菜单树
		getUserMenus();

		// 角色列表
		getUserRoles();

	}

	/**
	 * 登录用户菜单(树形结构数据)
	 */
	public static List getUserMenus() {
		User sysUser = getCacheLoginUser();

		List<Map> userMenus = new ArrayList();
		if (null != sysUser) {
			userMenus = sysResourceService.getResourceByUser(sysUser);
			
			getSession().setAttribute("userResource", userMenus);
			
			List treeList = TreeUtils2.toTreeNodeList(userMenus);
			ResultUtil.getSuccessResult(userMenus);
			getSession().setAttribute("userTreeResource", treeList);
			getSession().setAttribute("userJSONResource", JSON.toJSONString(treeList, SerializerFeature.WriteMapNullValue));
		}

		return userMenus;
	}

	public static List<Resources> getUserResourcesList() {

		Map<String, Resources> userResources = SysUserUtils.getUserResources();
		List<Resources> userResourceList = Lists.newArrayList();
		for (Resources res : userResources.values()) {
			// if(Constant.RESOURCE_TYPE_MENU.equals(res.getType())){
			// userResourceList.add(res);
			// }
		}

		return userResourceList;

	}

	/**
	 * 登录用户持有的资源（map集合数据， key为主键）
	 * 
	 * @return
	 */
	public static Map<String, Resources> getUserResources() {
		User sysUser = getCacheLoginUser();
		Map<String, Resources> userResources = CacheUtils.get(Constant.CACHE_SYS_RESOURCE,
				Constant.CACHE_USER_RESOURCE + sysUser.getAccount());
		if (userResources == null) {
			List<Resources> userRes = new ArrayList<Resources>();
			userResources = new LinkedHashMap<String, Resources>();
			if (isAdmin()) {
				// userRes = sysResourceService.select(new SysResource());
				// LinkedHashMap<String, SysResource> allRes =
				// sysResourceService.getAllResourcesMap();
				// userRes = new ArrayList<SysResource>(allRes.values());
			} else {
				// userRes =
				// sysResourceService.findUserResourceByUserId(sysUser);
			}

			for (Resources res : userRes) {
				// userResources.put(res.getId().toString(), res);
			}

			CacheUtils.put(Constant.CACHE_SYS_RESOURCE, Constant.CACHE_USER_RESOURCE + sysUser.getAccount(),
					userResources);
		}
		return userResources;
	}

	/**
	 * 登录用户的角色
	 */
	public static List getUserRoles() {
		User sysUser = getCacheLoginUser();

		List roles = new ArrayList();
		if (sysUser != null) {
			roles = sysRoleService.getRoleByUser(sysUser);

			getSession().setAttribute("userRole", roles);
		}
		return roles;
	}

	// 是否是超级管理员
	public static boolean isAdmin() {
		User sysUser = getCacheLoginUser();
		List<Map> userRoles =getUserRoles();

		boolean flag = false;
		for (Map aRole : userRoles) {
			if (PMSUtils.isNull(aRole.get("role_uuid")).equals("1")) {
				flag = true;
				break;
			}
		}

		if (sysUser.getAccount().equals("admin")) {
			return true;
		}
		return flag;
	}

	/**
	 * 清除缓存中用户认证
	 */
	public static void clearAllCachedAuthorizationInfo(List<String> userIds) {
		if (CollectionUtils.isNotEmpty(userIds)) {
			for (String userId : userIds) {
				boolean evictRes = CacheUtils.remove(Constant.CACHE_SYS_RESOURCE,
						Constant.CACHE_USER_RESOURCE + userId);

				boolean evictMenu = CacheUtils.remove(Constant.CACHE_SYS_RESOURCE, Constant.CACHE_USER_MENU + userId);

				boolean evictRole = CacheUtils.remove(Constant.CACHE_SYS_ROLE, Constant.CACHE_USER_ROLE + userId);

				if (evictRes && evictMenu && evictRole) {
					logger.debug("用户" + userId + "的菜单、资源、角色、机构、数据范围缓存全部删除");
				}
			}
		}
	}

	public static void clearCacheResource() {
		CacheUtils.clear(Constant.CACHE_SYS_RESOURCE);
	}

	/**
	 * 清除缓存中的用户
	 */
	public static void clearCacheUser(String userId) {
		CacheUtils.evict(Constant.CACHE_SYS_USER, userId);
	}

	/**
	 * 清除用户机构
	 */
	public static void clearCacheOffice(List<String> userIds) {
		for (String userId : userIds) {
			CacheUtils.evict(Constant.CACHE_SYS_OFFICE, Constant.CACHE_USER_OFFICE + userId);
		}
	}

	/**
	 * 缓存登录用户
	 */
	public static void setCacheLoginUser(User sysUser) {
		getSession().setAttribute(Constant.SESSION_LOGIN_USER, sysUser);
	}

	/**
	 * 从缓存中取登录的用户
	 */
	public static User getCacheLoginUser() {
		User user = (User) getSession().getAttribute(Constant.SESSION_LOGIN_USER);
		return user;
	}

	/**
	 * 得到当前session
	 */
	public static HttpSession getSession() {
		HttpSession session = getCurRequest().getSession();
		return session;
	}

	/**
	 * session中的用户
	 */
	public static User getSessionLoginUser() {
		return (User) getSession().getAttribute(Constant.SESSION_LOGIN_USER);
	}

	/**
	 * @Title: getCurRequest
	 * @Description:(获得当前的request)
	 * @param:@return
	 * @return:HttpServletRequest
	 */
	public static HttpServletRequest getCurRequest() {
		RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
		if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) {
			ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
			return servletRequestAttributes.getRequest();
		}
		return null;
	}
	

}
